﻿namespace SchemeFileSystem.Providers
{
    using System;
    using System.IO;
    using System.Linq;
    using System.Text;

    using Ionic.Zip;

    public class Chrome : IFilesystem
    {
        #region Fields

        private readonly ZipFile zip;

        #endregion

        #region Constructors and Destructors

        public Chrome()
        {
            this.zip = new ZipFile("chrome.ch");
        }

        #endregion

        #region Public Properties

        public override string[] Schemes
        {
            get
            {
                return new[] { "chrome://" };
            }
        }

        #endregion

        #region Public Methods and Operators

        public override void CreateFile(string path, string content)
        {
            var uri = new Uri(path);

            this.zip.AddEntry(Path.GetFileName(path), content);
            this.zip.Save("chrome.ch");
        }

        public override void CreateFolder(string path)
        {
            var uri = new Uri(path);

            this.zip.AddDirectoryByName(uri.Segments[1]);
            this.zip.Save("chrome.ch");
        }

        public override void Delete(string path)
        {
            this.zip.RemoveEntry(Path.GetFileName(path));
            zip.Save("chrome.ch");
        }

        public override void Mount(char pathletter, string path)
        {
        }

        public override void Unmount(char pathletter, string path)
        {
        }

        public override string[] GetFiles(string path)
        {
            return (from e in this.zip where e.FileName == Path.GetFileName(path) select e.FileName).ToArray();
        }

        public override string[] GetFolders(string path)
        {
            return new string[] { };
        }

        public override string ReadFile(string path)
        {
            foreach (ZipEntry e in this.zip)
            {
                if (e.FileName == Path.GetFileName(path))
                {
                    using (var ms = new MemoryStream())
                    {
                        e.Extract(ms);

                        return Encoding.Default.GetString(ms.ToArray());
                    }
                }
            }
            return null;
        }

        #endregion
    }
}